<template>
  <a-modal
    :confirm-loading="loading"
    :destroy-on-close="true"
    :mask-closable="false"
    :visible="visible"
    :title="title"
    @cancel="handleClose"
    @ok="handleSubmit"
  >
    <a-form ref="formRef" :label-col="{ span: 4 }" :model="formData" :rules="formRules" :wrapper-col="{ span: 20 }">
      <a-form-item label="用户名" name="username">
        <a-input v-model:value="formData.username" placeholder="请输入用户名(5-16位可包含 字母、数字、下划线)" />
      </a-form-item>
      <a-form-item label="密码" name="password">
        <a-input v-model:value="formData.password" type="password" placeholder="请输入密码" />
      </a-form-item>
      <a-form-item label="确认密码" name="confirmPassword">
        <a-input v-model:value="formData.confirmPassword" type="password" placeholder="请再次输入密码" />
      </a-form-item>
      <a-form-item label="真实姓名" name="realname">
        <a-input v-model:value="formData.realname" placeholder="请输入真实姓名" />
      </a-form-item>
      <a-form-item label="手机号码" name="phone">
        <a-input v-model:value="formData.phone" placeholder="请输入手机号码" />
      </a-form-item>
      <a-form-item label="电子邮箱" name="email">
        <a-input v-model:value="formData.email" placeholder="请输入电子邮箱" />
      </a-form-item>
      <a-form-item label="所属部门" name="deptId">
        <a-tree-select
          v-model:value="formData.deptId"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :tree-data="deptTreeData"
          placeholder="请选择所属部门"
          tree-default-expand-all
          allow-clear
        >
        </a-tree-select>
      </a-form-item>
      <a-form-item label="角色" name="role">
        <a-select
          v-model:value="formData.role"
          mode="multiple"
          placeholder="请选择角色"
          allow-clear
          style="width: 100%"
        >
          <template v-for="(value, key) in roleItems" :key="key">
            <a-select-option v-if="parseInt(key) > 1" :value="parseInt(key)">
              {{ value }}
            </a-select-option>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-radio-group v-model:value="formData.status" button-style="solid">
          <a-radio-button v-for="item in AvailableStatusEnum.$options()" :key="item.value" :value="item.value">{{
            item.label
          }}</a-radio-button>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script name="SystemUserEdit" lang="ts" setup>
import { getList } from "@/api/system/role";
import { phoneValidator, realnameValidator, usernameValidator } from "@/utils/validator";
import { getUser, saveUser, updateUser } from "@/api/system/user";
import { enum2Value } from "@/utils/conver";
import { AvailableStatusEnum } from "@/enums/common";

const emit = defineEmits(["reload"]);

const visible = ref(false);
const title = ref("");
const loading = ref(false);

const roleItems = ref<ObjectNum>({});
getList().then(response => {
  response.data.forEach(role => {
    roleItems.value[role.roleId] = role.roleName;
  });
});

const deptTreeData = inject("deptTreeData");
const formRef = ref();
const formData = reactive<any>({
  userId: undefined
});

const handleCheckRePwd = (rules: any, value: string) => {
  if (formData.password && formData.password !== value) {
    return Promise.reject("两次输入的密码不一致");
  } else {
    return Promise.resolve();
  }
};

const formRules = reactive({
  username: [
    { required: true, trigger: "blur", message: "请输入用户名" },
    { validator: usernameValidator, trigger: "blur" }
  ],
  password: [
    { required: true, trigger: "blur", message: "请输入密码" },
    { min: 5, trigger: "blur", message: "密码长度不能低于5位" }
  ],
  confirmPassword: [
    { required: true, trigger: "blur", message: "请再次输入新密码" },
    { validator: handleCheckRePwd, trigger: "blur" }
  ],
  realname: [
    { required: true, trigger: "blur", message: "请输入真实姓名" },
    { validator: realnameValidator, trigger: "blur" }
  ],
  phone: [
    { required: true, trigger: "blur", message: "请输入手机号" },
    { validator: phoneValidator, trigger: "blur" }
  ],
  deptId: [
    {
      type: `number`,
      required: true,
      trigger: ["change", "blur"],
      message: "请选择所属部门"
    }
  ]
});

const handleGetUser = (userId: number) => {
  loading.value = true;
  getUser(userId)
    .then(response => {
      Object.assign(formData, enum2Value(response.data));
      const roleIds: number[] = [];
      (response.data.roleList as Array<any>).forEach(item => {
        roleIds.push(item.roleId);
      });

      formData.role = roleIds;
      formData.password = "";
      formRules.password[0].required = false;
      formRules.confirmPassword[0].required = false;

      console.log(formData);
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleAdd = () => {
  Object.assign(
    formData,
    reactive({
      userId: undefined,
      username: "",
      password: "",
      confirmPassword: "",
      realname: "",
      phone: "",
      email: "",
      deptId: undefined,
      role: [],
      status: AvailableStatusEnum.ENABLE.code
    })
  );
  title.value = "添加用户";
  visible.value = true;
};

const handleEdit = (id: number) => {
  handleGetUser(id);
  title.value = "编辑用户";
  visible.value = true;
};

const handleClose = () => {
  formData.userId = undefined;
  formRef.value.resetFields();
  visible.value = false;
};

const handleSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      if (formData.userId === undefined) {
        saveUser(formData)
          .then(() => {
            antdMessage.success("添加成功");
            emit("reload");
            handleClose();
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        updateUser(formData)
          .then(() => {
            antdMessage.success("编辑成功");
            emit("reload");
            handleClose();
          })
          .finally(() => {
            loading.value = false;
          });
      }
    })
    .catch(error => {
      // console.log("error", error);
    });
};

defineExpose({
  handleAdd,
  handleEdit
});
</script>
